using CSV
using DataFrames
using Plots
using Statistics
using XLSX

# 读取 Excel 文件中的数据
filename = "result/Soft_Filter/filtered_data.csv"  # 替换为您的文件名
filename = "result/Active_Filter/Whole_Sys.csv"  # tmp

data = DataFrame(CSV.File(filename))

# tmp
point_numbers = data[:, 1]
timestamps = data[:, 2]
temperatures = data[:, 3]
measurements = data[:, 4]
moving_avg = data[:,5]
kf_data = data[:,6]
# # 提取各列数据
# point_numbers = data[:, 1]
# timestamps = data[:, 2]
# temperatures = data[:, 3]
# measurements = data[:, 4]
# moving_avg = data[:,5]
# kf_data = data[:,7]

window_size = 3000

function max_level_difference(data, window_size)
    n = length(data)
    max_diffs = []
    global_max_value = 0
    global_min_value = 0
    global_max_diff = 0

    for i in 1:(n - window_size + 1)
        # 提取当前窗口的数据
        window = data[i:(i + window_size - 1)]
        
        # 计算当前窗口内每相邻两个数据的级差
        # 计算最大值
        max_value = maximum(window)

        # 计算最小值
        min_value = minimum(window)
        level_diffs = max_value - min_value
        
        
        # 将最大级差添加到结果列表中
        push!(max_diffs, level_diffs)
        if (global_max_diff<level_diffs)
            global_max_value = max_value
            global_min_value = min_value
            global_max_diff = level_diffs
        end
    end

    return global_max_value,global_min_value,maximum(max_diffs)
end


function max_std(data, window_size)
    n = length(data)
    data_stds = []

    for i in 1:(n - window_size + 1)
        # 提取当前窗口的数据
        window = data[i:(i + window_size - 1)]
        
        # 计算当前窗口内每相邻两个数据的级差
        # 计算最大值
        data_std = std(window)        
        
        # 将最大级差添加到结果列表中
        push!(data_stds, data_std)
    end

    return maximum(data_stds)
end

measure_max,measure_min,max_diff_measure = max_level_difference(measurements, window_size)
ma_max,ma_min,max_diff_mean = max_level_difference(moving_avg[100:end], window_size)
kf_max,kf_min,max_diff_kf = max_level_difference(kf_data[100:end], window_size)

max_std_measure = max_std(measurements, window_size)
max_std_mean = max_std(moving_avg[100:end], window_size)
max_std_kf = max_std(kf_data[100:end], window_size)

# 输出结果
println("级差：")
println("原始数据5s内级差：$max_diff_measure")
println("滑动均值滤波后5s内级差：$max_diff_mean")
println("卡尔曼滤波后5s内级差：$max_diff_kf")
println("标准差：")
println("原始数据5s内级差：$max_std_measure")
println("滑动均值滤波后5s内级差：$max_std_mean")
println("卡尔曼滤波后5s内级差：$max_std_kf")
# println(max_diffs)

# 绘制原始数据和滤波后的数据
# filtered_data = DataFrame(
#     Point_Number=point_numbers,
#     Timestamp=timestamps,
#     Temperature=temperatures,
#     Original_Measurement=measurements,
#     Max_Diffs = max_diffs,
# )
# output_filename = "级差.csv"
# CSV.writetable(output_filename, filtered_data)
